<?php
namespace App\Api\Controllers\Changsha;


use App\Models\TfConfig;
use App\Models\TfStore;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Support\Facades\Log;

class PayController extends BaseController
{

    //扫一扫 0-系统错误 1-成功 2-正在支付 3-失败
    public function scan_pay($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $device_id = $data['device_id'];
            $shop_name = $data['shop_name'];
            $notify_url = $data['notify_url'];

            $ECustId = $data['ECustId'];
            $DeptId = $data['DeptId'];
            $StaffId = $data['StaffId'];

            $PayMethod = $data['PayMethod'];
            $Longitude = $data['Longitude'];
            $Latitude = $data['Latitude'];

            $data = [
                'Service_version' => "1.0",
                'ECustId' => $ECustId,
                'DeptId' => $DeptId,
                'StaffId' => $StaffId,
                'MerchOrder' => $out_trade_no,
                'OrderAmount' => $total_amount,
                'PayMethod' => $PayMethod,
                'CardNo' => $code,
                'BackUrl' => $notify_url,
                'Longitude' => $Longitude,
                'Latitude' => $Latitude,
                'DeviceId' => $device_id,
            ];

            $obj = new \App\Api\Controllers\Changsha\BaseController();
            $url = $obj->BC;
            $string = $obj->getSignContent($data);
            $string = md5($string);
            $data['Sign'] = $obj->sign($string);

            $re = $obj->curl_form($url, $data);
            $re = json_decode($re, true);
            //交易成功
            if ($re['STATUS'] == '0000') {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => $re
                ];
            } //用户输入密码
            elseif ($re['STATUS'] == '0008') {
                return [
                    'status' => 2,
                    'message' => '请用户输入密码',
                    'data' => $re
                ];
            }
            else {
                return [
                    'status' => 0,
                    'message' => $re['MSG']
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款 5 退款中
    public function order_query($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $ECustId = $data['ECustId'];

            $data = [
                'Service_version' => "1.0",
                'ECustId' => $ECustId,
                'MerchOrder' => $out_trade_no,
            ];

            $obj = new \App\Api\Controllers\Changsha\BaseController();
            $url = $obj->ORDERQUERY;
            $string = $obj->getSignContent($data);
            $string = md5($string);
            $data['Sign'] = $obj->sign($string);
            $re = $obj->curl_form($url, $data);
            $re = json_decode($re, true);
            //业务成功
            if ($re['STATUS'] == '0000') {
                if ($re['OrderStat'] == "8" || $re['OrderStat'] == "0") {
                    //用户输入密码
                    return [
                        'status' => 2,
                        'message' => '请用户输入密码',
                        'data' => $re
                    ];
                }
                elseif ($re['OrderStat'] == "1") {
                    return [
                        'status' => 1,
                        'message' => '交易成功',
                        'data' => $re
                    ];
                }
                else {
                    return [
                        'status' => 0,
                        'message' => $re['MSG']
                    ];
                }
            } else {
                return [
                    'status' => 0,
                    'message' => $re['MSG']
                ];
            }

        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data)
    {
        try {
            return [
                'status' => '0',
                'message' => '暂不支持退款'
            ];

            $OrderId = $data['OrderId'];
            $refundAmount = $data['refundAmount'];
            $ECustId = $data['ECustId'];

            $data = [
                'Service_version' => "1.0",
                'ECustId' => $ECustId,
                'OrderId' => $OrderId,
                'CancelReason'=>'正常退款',
                'RefundAmount' => $refundAmount,
            ];

            $obj = new \App\Api\Controllers\Changsha\BaseController();
            $url = $obj->REFUND;
            $string = $obj->getSignContent($data);
            $string = md5($string);
            $data['Sign'] = $obj->sign($string);
            $re = $obj->curl_form($url, $data);
            $re = json_decode($re, true);

            //业务成功
            if ($re['STATUS'] == "0000") {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re,
                ];

            }
            else {
                return [
                    'status' => 0,
                    'message' => $re['MSG'],
                ];
            }

        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {
            $refund_trade_no = $data['refund_trade_no'];
            $sub_mch_id = $data['sub_mch_id'];
            $mch_id = $data['mch_id'];
            $pub_key = $data['pub_key'];
            $pri_key = $data['pri_key'];
            $date = $data['date'];

            $post_data = [
                'sub_mch_id' => $sub_mch_id,
                'refund_trade_no' => $refund_trade_no,
                'date' => $date,
            ];

            $method = '/openapi/merchant/pay/refund-query';
            $obj = new BaseController();
            $obj->mch_id = $mch_id;
            $obj->pub_key = $pub_key;
            $obj->pri_key = $pri_key;
            $re = $obj->api($post_data, $method, false);

            //系统错误
            if ($re['code'] != "0") {
                return [
                    'status' => 0,
                    'message' => $re['msg'],

                ];
            }
            //业务成功
            if ($re['data']['trade_status'] != 3) {

                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => $re['data'],
                ];


            } else {
                return [
                    'status' => 0,
                    'message' => '退款失败',
                    'data' => $re['data'],
                ];
            }

        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //生成动态二维码-公共
    public function send_qr($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $total_amount = $data['total_amount'];
            $remark = $data['remark'];
            $notify_url = $data['notify_url'];
            $url = $data['request_url'];
            $returnParams = $data['return_params'];//原样返回
            $md_key = $data['md_key'];
            $mid = $data['mid'];
            $orgNo = $data['orgNo'];
            $payChannel = $data['payChannel'];
            //请求数据

            $data = [
                'mid' => $mid,
                'totalFee' => $total_amount,
                'outTradeNo' => $out_trade_no,
                'nonceStr' => $out_trade_no,
                'payChannel' => $payChannel,
                'notifyUrl' => $notify_url,
                'orgNo' => $orgNo,
            ];

            //和融通交易接口
            $this->md_key = $md_key;
            $re = $this->execute($data, $url);
            //系统错误
            if ($re['resultCode'] == "fail") {
                return [
                    'status' => 0,
                    'message' => $re['errDes'],

                ];
            }

            if ($re['resultCode'] == "success") {
                return [
                    'status' => 1,
                    'code_url' => $re['codeUrl'],
                    'message' => $re,

                ];
            }


        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //静态码提交-公共
    public function qr_submit($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $open_id = $data['open_id'];
            $total_amount = $data['total_amount'];
            $remark = $data['remark'];
            $device_id = $data['device_id'];
            $shop_name = $data['shop_name'];
            $notify_url = $data['notify_url'];

            $sub_mch_id = $data['sub_mch_id'];
            $mch_id = $data['mch_id'];
            $pub_key = $data['pub_key'];
            $pri_key = $data['pri_key'];
            $channel = $data['channel'];
            $post_data = [
                'sub_mch_id' => $sub_mch_id,
                'channel' => $channel,
                'client_ip' => get_client_ip(),
                'total_fee' => $total_amount,
                'out_trade_no' => $out_trade_no,
                'body' => $shop_name,
                'store_id' => $sub_mch_id,
                'terminal_id' => $device_id,
                'openid' => $open_id,
                'notify_url' => $notify_url,
            ];

            if ($channel == "WECHAT_MP") {
                $post_data['wx_appid'] = $data['wx_appid'];
            }
            $method = '/openapi/merchant/pay/gateway';
            $obj = new BaseController();
            $obj->mch_id = $mch_id;
            $obj->pub_key = $pub_key;
            $obj->pri_key = $pri_key;
            $re = $obj->api($post_data, $method, false);

            //系统错误
            if ($re['code'] != "0") {
                return [
                    'status' => 0,
                    'message' => $re['msg'],

                ];
            }

            //如果是失败报备一下
            if (isset($re['data']['trade_status']) && $re['data']['trade_status'] == 6) {
                $method = '/openapi/merchant/open';

                $TfStore = TfStore::where('sub_mch_id', $sub_mch_id)
                    ->select('config_id', 'qd')
                    ->first();

                $TfConfig = TfConfig::where('config_id', $TfStore->config_id)
                    ->where('qd', $TfStore->qd)
                    ->select('alipay_pid', 'wechat_channel_no')
                    ->first();
                if (!$TfConfig) {
                    $TfConfig = TfConfig::where('config_id', '1234')
                        ->where('qd', $TfStore->qd)
                        ->select('alipay_pid', 'wechat_channel_no')
                        ->first();
                }

                //传化支付宝报备
                $post_data = [
                    'sub_mch_id' => $sub_mch_id,
                    'channel' => '0',
                    'alipay_pid' => $TfConfig->alipay_pid
                ];

                $re1 = $obj->api($post_data, $method, false);
                //传化微信报备
                $post_data = [
                    'sub_mch_id' => $sub_mch_id,
                    'channel' => '1',
                    'wechat_channel_no' => $TfConfig->wechat_channel_no
                ];

                $re2 = $obj->api($post_data, $method, false);
            }

            return [
                'status' => 1,
                'message' => $re['msg'],
                'data' => $re['data']
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //订单关闭
    public function order_close($data)
    {
        try {
            $out_trade_no = $data['out_trade_no'];
            $url = $data['request_url'];
            $md_key = $data['md_key'];
            $mid = $data['mid'];
            $orgNo = $data['orgNo'];

            //请求数据
            $data = [
                'mid' => $mid,
                'nonceStr' => $out_trade_no,
                'outTradeNo' => $out_trade_no,
                'orgNo' => $orgNo,
            ];

            //和融通交易接口
            $this->md_key = $md_key;
            $re = $this->execute($data, $url);

            //系统错误
            if ($re['resultCode'] == "fail") {
                return [
                    'status' => 0,
                    'message' => $re['errDes'],

                ];
            }

            //业务成功
            if ($re['resultCode'] == "success") {

                //交易成功
                return [
                    'status' => 1,
                    'message' => '关闭成功',
                    'data' => $re,
                ];

            }
            else {
                return [
                    'status' => 0,
                    'message' => $re['errDes']
                ];
            }

        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


}
